(function ($) {

    $.fn.webexcel.plus.cell = function (target) {

        var state = $.data(target, "webexcel"), opts = state.options;

        //设置单元格边框
        opts.setBorderSize = function (status) {
            for (var key in opts.chooseCellOption.cells) {
                var cell = opts.chooseCellOption.cells[key];
                switch (status) {
                    case 1://无框线
                        cell.borderColor = opts.contentBorderColor;
                        cell.border = cell.borderLeft = cell.borderTop = cell.borderRight = cell.borderBottom = false;
                        break;
                    case 2://所有框线
                        cell.borderColor = opts.setBorderColor;
                        cell.border = cell.borderLeft = cell.borderTop = cell.borderRight = cell.borderBottom = true;
                        break;
                    case 3://外框线
                        break;
                    case 4://上框线
                        break;
                    case 5://下框线
                        break;
                    case 6://左框线
                        break;
                    case 7://右框线
                        break;
                    case 8://上下框线
                        break;
                    case 9://左右框线
                        break;
                }
                opts.clearCanvasCell(opts.contentContext, cell);
                opts.drawCanvasCell(opts.contentContext, cell);
            }
        };

        //拆分单元格
        opts.splitChooseCell = function () {
            var mergeCell = opts.findChooseMergeCell(state, opts);
            if (mergeCell) {
                opts.clearCanvasCell(opts.contentContext, mergeCell);
                var minRow = mergeCell.beginRow;
                var maxRow = mergeCell.endRow;
                var minCol = mergeCell.beginCol;
                var maxCol = mergeCell.endCol;
                for (var i = minRow; i <= maxRow; i++) {
                    for (var j = minCol; j <= maxCol; j++) {
                        var indexRowCell = opts.data.indexRowData['indexRow_r0_c' + j];
                        var indexColCell = opts.data.indexColData['indexCol_r' + i + '_c0'];
                        var cell = opts.data.contentData['content_r' + i + '_c' + j];
                        cell.mergeId = null;
                        cell.showCell = true;
                        cell.merged = false;
                        cell.w = indexRowCell.w;
                        cell.h = indexColCell.h;
                        cell.endRow = cell.beginRow;
                        cell.endCol = cell.beginCol;
                        opts.data.contentData[cell.id] = cell;
                        opts.drawCanvasCell(opts.contentContext, cell);
                    }
                }
            }
        };

        //合并单元格
        opts.mergeChooseCell = function () {
            var mergeCell = opts.findChooseMergeCell(state, opts);
            if (mergeCell) {
                //重新画合并单元格
                opts.data.contentData[mergeCell.id] = mergeCell;
                opts.clearCanvasCell(opts.contentContext, mergeCell);
                opts.drawCanvasCell(opts.contentContext, mergeCell);
            }
        };

        //查找选择的单元格
        opts.findChooseMergeCell = function (state, opts) {
            var co = opts.chooseCellOption;
            var mergeCell = null;
            if (co) {
                for (var i = co.beginRow; i <= co.endRow; i++) {
                    for (var j = co.beginCol; j <= co.endCol; j++) {
                        var cell = opts.data.contentData['content_r' + i + '_c' + j];
                        if (i == co.beginRow && j == co.beginCol) {
                            //如果是第一个单元格保留
                            mergeCell = cell;
                            //重设合并单元格属性
                            cell.w = co.width;
                            cell.h = co.height;
                            cell.endRow = co.endRow;
                            cell.endCol = co.endCol;
                            cell.merged = true;
                        } else {
                            //其余的标记被合并的单元格的ID
                            cell.mergeId = mergeCell.id;
                            cell.showCell = false;
                        }
                    }
                }
            }
            return mergeCell;
        };

        //画选择框，opts.mouseDown和opts.mouseMove需要相对于容器的坐标
        opts.drawChooseBox = function () {
            if (opts.mouseDown && opts.mouseMove) {
                //先得到选择的两个点的大小
                var minX = opts.mouseDown.x;
                var maxX = opts.mouseMove.x;
                if (minX > opts.mouseMove.x) {
                    minX = opts.mouseMove.x;
                    maxX = opts.mouseDown.x;
                }
                var minY = opts.mouseDown.y;
                var maxY = opts.mouseMove.y;
                if (minY > opts.mouseMove.y) {
                    minY = opts.mouseMove.y;
                    maxY = opts.mouseDown.y;
                }
                //转换为画布坐标
                var minDot = {x: minX, y: minY};//根据窗口最小坐标获取画布坐标
                minDot = opts.dotCalculate(minDot, opts.contentCanvasDot, 0);
                minDot = opts.dotCalculate(minDot, opts.scrollDot, 1);
                var maxDot = {x: maxX, y: maxY};//根据窗口最大坐标获取画布坐标
                maxDot = opts.dotCalculate(maxDot, opts.contentCanvasDot, 0);
                maxDot = opts.dotCalculate(maxDot, opts.scrollDot, 1);

                //保存画布坐标
                opts.chooseCellOption = {
                    minX: 0,
                    minY: 0,
                    maxX: 0,
                    maxY: 0,
                    beginRow: 0,
                    endRow: 0,
                    beginCol: 0,
                    endCol: 0,
                    width: 0,
                    height: 0,
                    cells: [],
                    hasMergeCell: false,
                    cellCount: 0//选择框内共多少单元格,
                };
                //遍历索引行，取矩形框的最大和最小X坐标
                for (var rowKey in opts.data.indexRowData) {
                    var rowData = opts.data.indexRowData[rowKey];
                    if (minDot.x >= rowData.x && minDot.x <= rowData.x + rowData.w) {
                        opts.chooseCellOption.minX = rowData.x;
                        opts.chooseCellOption.beginCol = rowData.beginCol;
                    }
                    if (maxDot.x >= rowData.x && maxDot.x <= rowData.x + rowData.w) {
                        opts.chooseCellOption.maxX = rowData.x + rowData.w;
                        opts.chooseCellOption.endCol = rowData.endCol;
                    }
                }
                //遍历索引列，取矩形框的最大和最小Y坐标
                for (var colKey in opts.data.indexColData) {
                    var colData = opts.data.indexColData[colKey];
                    if (minDot.y >= colData.y && minDot.y <= colData.y + colData.h) {
                        opts.chooseCellOption.minY = colData.y;
                        opts.chooseCellOption.beginRow = colData.beginRow;
                    }
                    if (maxDot.y >= colData.y && maxDot.y <= colData.y + colData.h) {
                        opts.chooseCellOption.maxY = colData.y + colData.h;
                        opts.chooseCellOption.endRow = colData.endRow;
                    }
                }
                //遍历范围内的单元格，判断是否有合并过的单元格，如果有合并的单元格，则取合并单元格的信息
                for (var i = opts.chooseCellOption.beginRow; i <= opts.chooseCellOption.endRow; i++) {
                    for (var j = opts.chooseCellOption.beginCol; j <= opts.chooseCellOption.endCol; j++) {
                        var cell = opts.data.contentData['content_r' + i + '_c' + j];
                        if (i == opts.chooseCellOption.beginRow && j == opts.chooseCellOption.beginCol) {
                            opts.chooseFirstCell = cell;//获取第一个有效单元格
                        }
                        if (cell != null) {
                            if (cell.mergeId || cell.merged) {
                                //如果单元格被合并了，则查找被合并的单元格坐标
                                if (cell.mergeId) {
                                    cell = opts.data.contentData[cell.mergeId];
                                }
                                opts.chooseCellOption.hasMergeCell = true;
                                opts.chooseFirstCell = cell;//获取第一个有效单元格
                            }
                            if (cell.x < opts.chooseCellOption.minX) {
                                opts.chooseCellOption.minX = cell.x;
                                opts.chooseCellOption.beginCol = cell.beginCol;
                            }
                            if (cell.y < opts.chooseCellOption.minY) {
                                opts.chooseCellOption.minY = cell.y;
                                opts.chooseCellOption.beginRow = cell.beginRow;
                            }
                            if (cell.x + cell.w > opts.chooseCellOption.maxX) {
                                opts.chooseCellOption.maxX = cell.x + cell.w;
                                opts.chooseCellOption.endCol = cell.endCol;
                            }
                            if (cell.y + cell.h > opts.chooseCellOption.maxY) {
                                opts.chooseCellOption.maxY = cell.y + cell.h;
                                opts.chooseCellOption.endRow = cell.endRow;
                            }
                            opts.chooseCellOption.cellCount++;
                            opts.chooseCellOption.cells.push(cell);
                        }
                    }
                }
                opts.chooseCellOption.width = opts.chooseCellOption.maxX - opts.chooseCellOption.minX;
                opts.chooseCellOption.height = opts.chooseCellOption.maxY - opts.chooseCellOption.minY;
                var dot = {x: opts.chooseCellOption.minX, y: opts.chooseCellOption.minY};
                dot = opts.dotCalculate(dot, opts.contentCanvasDot, 1);
                var size = Math.ceil(opts.cellDefault.borderSize / 2);//解决小数像素偏差问题
                //窗口坐标选择框样式
                opts.chooseBoxCss = {
                    left: dot.x - size,
                    top: dot.y - size,
                    width: opts.chooseCellOption.width - opts.chooseBorderSize * 2 + size * 2,
                    height: opts.chooseCellOption.height - opts.chooseBorderSize * 2 + size * 2,
                    border: opts.chooseBorderSize + 'px solid ' + opts.chooseBorderColor
                };
                opts.chooseBox.css(opts.chooseBoxCss).show();
            }
        };

        //监听页面按键启用编辑框
        opts.listenEditInputKeyUp = function (state, opts, e) {
            function enableKey(e) {
                if (e.keyCode >= 48 && e.keyCode <= 57) {
                    return e.key;
                } else if (e.keyCode >= 65 && e.keyCode <= 90) {
                    return e.key;
                } else if (e.keyCode >= 65 && e.keyCode <= 90) {
                    return e.key;
                } else if (e.keyCode >= 96 && e.keyCode <= 111) {
                    return e.key;
                } else if (e.keyCode >= 186 && e.keyCode <= 221) {
                    return e.key;
                }
                return "";
            }

            var text = enableKey(e);
            if (text && opts.chooseBox.is(':visible') && (
                opts.chooseCellOption.cellCount <= 1 ||
                opts.chooseCellOption.hasMergeCell) && (
                document.activeElement == document.body ||
                document.activeElement == opts.editInput[0])) {
                //设置输入框显示
                opts.chooseBox.hide();
                opts.editInput.attr('cell-id', opts.chooseFirstCell.id);
                opts.changeEditInputCss(state, opts);
                opts.editInput.val(opts.chooseFirstCell.text);
            }
        };

        //动态修改编辑框长度
        opts.changeEditInputCss = function (state, opts) {
            //打开编辑框
            opts.editCss = {
                left: opts.chooseBoxCss.left,
                top: opts.chooseBoxCss.top,
                width: opts.chooseBoxCss.width,
                height: opts.chooseBoxCss.height,
                border: opts.editBorderSize + 'px solid ' + opts.editBorderColor
            };
            var textW = opts.contentContext.measureText(opts.editInput.val()).width;
            textW = textW + opts.chooseFirstCell.padding * 2 + 50;
            if (textW >= opts.chooseBoxCss.width) {
                opts.editCss.width = textW;
            }
            //处理超出边界的情况
            var clientWidth = document.body.clientWidth + opts.scrollDot.x;
            if (opts.editCss.left + opts.editCss.width > clientWidth) {
                opts.editCss.width = clientWidth - opts.editCss.left - 20;
                opts.editInput.textareaAutoHeight();
            }
            opts.editInput.css(opts.editCss).show().focus();
        };

        //jquery增加textarea自动设置高度方法
        $.fn.extend({
            textareaAutoHeight: function () {
                return this.each(function () {
                    var $this = $(this);
                    if (!$this.attr('initAttrH')) {
                        $this.attr('initAttrH', $this.outerHeight());
                    }
                    setAutoHeight(this).on('input', function () {
                        setAutoHeight(this);
                    }).on('focus', function () {
                        setAutoHeight(this);
                    });
                });

                function setAutoHeight(elem) {
                    var $obj = $(elem);
                    return $obj.css({height: $obj.attr('initAttrH'), 'overflow-y': 'hidden'}).height(elem.scrollHeight);
                }
            }
        });
    };

})(jQuery);